package com.md24housecall.activity;

import java.io.File;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Display;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.md24housecall.manager.CacheManager;
import com.md24housecall.manager.DimenManager;
import com.md24housecall.net.UrlBuilder;
import com.md24housecall.util.GlobalConstant;
import com.md24housecall.util.MyLog;
import com.md24housecall.util.Utils;
import com.md24housecall.view.RatioImageView;

public class WelcomeActivity extends Activity {
	private Thread mThread;
	private int TIMESLEEP = 3000;
	private AQuery aQuery;
	private GlobalConstant constant = GlobalConstant.getInstance();
	private String mediaType = "";
	private String mediaUrl = "";
	private Utils util = Utils.getInstance();
	private RatioImageView imvBackground;
	private String localFileName = "";
	private ProgressBar mProgressBar;
	private TextView txvLoading;
	private CacheManager cacheManager;
	

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.welcome);
		Display mDisplay = getWindowManager().getDefaultDisplay();
		constant.width = mDisplay.getWidth();
		constant.heigth = mDisplay.getHeight();
		constant.bg_ChoosePeople = "";
		constant.btn_ChoosePeople1 = "";
		constant.btn_ChoosePeople2 = "";
		constant.btn_ChoosePeople3 = "";
		constant.btn_ChoosePeople4 = "";
		mProgressBar=(ProgressBar)findViewById(R.id.progBarLoading);
		mProgressBar.setIndeterminate(true);
		LayoutParams param=(RelativeLayout.LayoutParams)mProgressBar.getLayoutParams();
		param.topMargin=(1160 * constant.width) / DimenManager.WIDTH_SPLASH;
		mProgressBar.setLayoutParams(param);
		txvLoading=(TextView)findViewById(R.id.txvLoading);
		LayoutParams params=(RelativeLayout.LayoutParams)txvLoading.getLayoutParams();
		params.topMargin=(1200 * constant.width) / DimenManager.WIDTH_SPLASH;
		txvLoading.setLayoutParams(params);
		
		imvBackground = (RatioImageView) findViewById(R.id.image);
		imvBackground.setRatio(DimenManager.WIDTH_SPLASH,  DimenManager.HEIGHT_SPLASH);
		
		if (aQuery == null)
			aQuery = new AQuery(this);
		cacheManager=CacheManager.getInstance(this);
		localFileName = util.getUrl(this);
		
		File f = new File(constant.file, localFileName);
		if (localFileName.equals("") || !f.exists()) {
			imvBackground.setBackgroundResource(R.drawable.default_welcome);
		} else {
			Bitmap bitmap = util.getBitmapFromFile(f);
			if(bitmap != null)
				imvBackground.setImageBitmap(bitmap);
			else
				imvBackground.setBackgroundResource(R.drawable.default_welcome);
		}
		getUrlFromApi();
		util.getPartnerCategoryFromApi(aQuery, cacheManager,false);
		util.getPartnerFromApi(aQuery, cacheManager,false);
		fordwardMainScreen();
	}
	
	private void getUrlFromApi() {
		// get background url
		aQuery.ajax(UrlBuilder.GETIMAGEAPIURL, JSONArray.class,new AjaxCallback<JSONArray>() {
					@Override
					public void callback(String url, JSONArray jsonArray,AjaxStatus status) {
						// TODO Auto-generated method stub
						super.callback(url, jsonArray, status);
						if(status.getCode()==200){
							if (jsonArray != null) {
								int len = jsonArray.length();
								for (int i = 0; i < len; i++) {
									try {
										JSONObject json_data = jsonArray.getJSONObject(i);
										mediaUrl = json_data.getString("guid");
										mediaType = json_data.getString("media_type");
										saveImageByDownloadManager(mediaUrl,Integer.parseInt(mediaType));
									} catch (Exception e) {
										// TODO Auto-generated catch block
										MyLog.d(GlobalConstant.TAG, "exception getUrlFromApi: "+e.getMessage());
									}
								}
							}
						} else {
							if(status.getCode()==-103)
								util.saveUrl(WelcomeActivity.this, "");
						}
					}
				});

	}

	private void saveImageByDownloadManager(String url, int type) {
		String fileName = url.substring(url.lastIndexOf("/"));
		String fullpath="TeleMedicine"+fileName;
		switch (type) {
		case 1:
			util.saveUrl(WelcomeActivity.this, fullpath);
			break;
		case 2:
			constant.bg_ChoosePeople = fullpath;
			break;
		case 3:
			constant.btn_ChoosePeople1 = fullpath;
			break;
		case 4:
			constant.btn_ChoosePeople2 = fullpath;
			break;
		case 5:
			constant.btn_ChoosePeople3 = fullpath;
			break;
		case 6:
			constant.btn_ChoosePeople4 = fullpath;
			break;
		}
		try {
				File downloadFile = new File(Environment.getExternalStorageDirectory()+"/TeleMedicine");
				if (!downloadFile.exists()) {
					downloadFile.mkdirs();
				}
				File target=new File(downloadFile.getAbsolutePath()+"/"+fileName);
				if(!target.exists()){
				DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
				Request request = new Request(Uri.parse(url));
				request.setDestinationUri(Uri.fromFile(target));
				request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
	//			request.setShowRunningNotification(false);
				downloadManager.enqueue(request);
			}

		} catch (Exception e) {
			MyLog.d(GlobalConstant.TAG, "exception download manager: " + e.getMessage());
		}
	}

	private void fordwardMainScreen() {
		mThread = new Thread(new Runnable() {

			public void run() {
				// TODO Auto-generated method stub
				try {
					Thread.sleep(TIMESLEEP);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				startActivity(new Intent(WelcomeActivity.this,
						HomeActivity.class));
				finish();
			}
		});
		mThread.start();
	}
	
}
